package com.cqs.example.io.example2;

import com.alibaba.fastjson.util.IOUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class BioClient2 {

    private static final int PORT = 8020;
    private static final String HOST = "127.0.0.1";


    private static AtomicLong cnt = new AtomicLong();
    private final Long clientId = cnt.addAndGet(1);

    public void chat() {

        Socket socket = null;
        OutputStream os = null;
        InputStream in = null;
        try {
            socket = new Socket(HOST, PORT);
            String msg = String.format("msg-%d", clientId);
            os = socket.getOutputStream();
            os.write(msg.getBytes(Charset.defaultCharset()));
            TimeUnit.SECONDS.sleep(1);
            in = socket.getInputStream();
            byte[] inMsg = new byte[in.available()];
            socket.getInputStream().read(inMsg);
            log.info("client:{} receive msg:{}", clientId, new String(inMsg));
        } catch (Exception e) {
            log.warn("socket通信异常", e);
        } finally {
            IOUtils.close(socket);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(10);
        long start = System.currentTimeMillis();
        int size = 10;
        CountDownLatch count = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    new BioClient2().chat();
                    count.countDown();
                }
            });
        }
        count.await();
        System.out.println("开销:"+(System.currentTimeMillis() - start)+"毫秒");
        exec.shutdown();
    }

}